package com.atguigu.classroom.wechat.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.classroom.exception.ClassroomException;
import com.atguigu.classroom.model.wechat.Menu;
import com.atguigu.classroom.vo.wechat.MenuVo;
import com.atguigu.classroom.wechat.mapper.MenuMapper;
import com.atguigu.classroom.wechat.service.MenuService;
import com.atguigu.classroom.wechat.utils.HttpClientUtils;
import com.atguigu.classroom.wechat.utils.WeChatPropertiesUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单明细 订单明细 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-07-17
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private WxMpService wxMpService;

    @Override
//    @Cacheable(value = "weChatMenu",key="#root.methodName")
    public List<Menu> findOneMenuInfo() {
        LambdaQueryWrapper<Menu> menuQueryWrapper=new LambdaQueryWrapper<>();
        menuQueryWrapper.eq(Menu::getParentId,0);
        List<Menu> menuList = menuMapper.selectList(menuQueryWrapper);
        return menuList;
    }

    @Override
//    @Cacheable(value = "weChatMenu",key="#root.methodName")
    public List<MenuVo> findMenuInfo() {
        List<Menu> menuList = menuMapper.selectList(null);
        List<Menu> oneMenuList=menuList.stream().filter(menu ->
            menu.getParentId().longValue()==0
        ).collect(Collectors.toList());
        List<MenuVo> menuVoList=oneMenuList.stream().map(oneMenu->{
            MenuVo menuVo=new MenuVo();
            BeanUtils.copyProperties(oneMenu,menuVo);
            return menuVo;
        }).collect(Collectors.toList());
        Map<Long,List<MenuVo>> secondMenuListMap=new HashMap<>(oneMenuList.size());
        //key是menuVo的parentId，value是一级menuVo的子menuVo集合
        menuList.stream().map(menu -> {
            if(menu.getParentId()!=0){
                if(!secondMenuListMap.containsKey(menu.getParentId())){
                    secondMenuListMap.put(menu.getParentId(),new ArrayList<>());
                }
                MenuVo menuVo=new MenuVo();
                BeanUtils.copyProperties(menu,menuVo);
                secondMenuListMap.get(menu.getParentId()).add(menuVo);
            }
            return null;
        }).collect(Collectors.toList());
        menuVoList.stream().map(menuVo -> {
            if(secondMenuListMap.containsKey(menuVo.getId())){
                menuVo.setChildren(secondMenuListMap.get(menuVo.getId()));
            }
            return null;
        }).collect(Collectors.toList());
        return menuVoList;
    }

    @Override
    public String getAccessToken() {
        StringBuffer stringBuffer=new StringBuffer();https:
        stringBuffer.append("https://api.weixin.qq.com/cgi-bin/token");
        stringBuffer.append("?grant_type=client_credential");
        stringBuffer.append("&appid=%s");
        stringBuffer.append("&secret=%s");
        //%s表示占位符里面需要传参数,配合String.format()传入参数
        String url = String.format(
                String.valueOf(stringBuffer),
                WeChatPropertiesUtils.MPAPPID,
                WeChatPropertiesUtils.MPAPPSECRET);
        try {
            String token = HttpClientUtils.get(url);
            JSONObject jsonObject = JSONObject.parseObject(token);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String syncMenu() {
        List<MenuVo> menuInfoList = this.findMenuInfo();
        JSONArray buttonList = new JSONArray();
        for(MenuVo oneMenuVo : menuInfoList) {
            JSONObject one = new JSONObject();
            one.put("name", oneMenuVo.getName());
            JSONArray subButton = new JSONArray();
            for(MenuVo twoMenuVo : oneMenuVo.getChildren()) {
                JSONObject view = new JSONObject();
                view.put("type", twoMenuVo.getType());
                if(twoMenuVo.getType().equals("view")) {
                    view.put("name", twoMenuVo.getName());
                    view.put("url", "http://5849c22c.r2.vip.cpolar.cn/#"+twoMenuVo.getUrl());//"ggkt2.vipgz1.91tunnel.com/#"+
                } else {
                    view.put("name", twoMenuVo.getName());
                    view.put("key", twoMenuVo.getMeunKey());
                }
                subButton.add(view);
            }
            one.put("sub_button", subButton);
            buttonList.add(one);
        }
        //菜单
        JSONObject button = new JSONObject();
        button.put("button", buttonList);
        try {
            String menuId = wxMpService.getMenuService().menuCreate(button.toJSONString());
            return menuId;
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new ClassroomException(20001,"公众号菜单同步失败");
        }
    }

    @Override
    public void removeMenu() {
        try {
            wxMpService.getMenuService().menuDelete();
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new ClassroomException(20001,"公众号菜单删除失败");
        }
    }
}
